import { getMasterBrandList, getMakeListByMaster } from "@/api/carList";

const state = {
  brand: {},
  letters: [],
  brandCars: [],
  yearList: {},
};

const mutations = {
  setBrand(state, obj) {
    state.brand = { ...obj };
  },
  setLetters(state, letters) {
    state.letters = letters;
  },
  setBrandCars(state, brandCars) {
    state.brandCars = brandCars;
  },
  setYearList(state, yearList) {
    state.yearList = yearList;
  },
};

const actions = {
  async init({ commit }) {
    let res = await getMasterBrandList();
    let brand = {};
    let letters = [];
    res.forEach((item) => {
      const initial = item.Spelling.slice(0, 1);
      if (brand[initial]) {
        brand[initial].push(item);
      } else {
        brand[initial] = [item];
      }
      letters.push(initial);
    });
    // const quchong = {};
    // const newarr = [];
    // letters.forEach(item=>{
    //   if(!quchong[item]){
    //     quchong[item] = item
    //     newarr.push(item)
    //   }
    //   // 利用对象键名的唯一性去重
    // })
    letters = Array.from(new Set(letters));
    // console.log(letters);
    commit("setBrand", brand); //拿到对象，键名是字母，键值是首字母下的所有车品牌
    commit("setLetters", letters); //拿到26个字母
  },
  // 获取品牌车系
  async getBrandCars({ commit }, params) {
    let res = await getMakeListByMaster(params);
    commit("setBrandCars", res);
  },
};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
};
